package com.sharainy.contoller;

import com.alibaba.fastjson.JSONObject;
import com.sharainy.pojo.*;
import com.sharainy.service.MerchantService;
import com.sharainy.service.RechargeService;
import com.sharainy.service.SettlementService;
import com.sharainy.util.DateUtil;
import com.sharainy.util.RestResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.*;

@Controller
@RequestMapping("/query")
public class QueryCompanyController {

    @Autowired
    private MerchantService merchantService;
    @Autowired
    private SettlementService settlementService;
    @Autowired
    private RechargeService rechargeService;
    @RequestMapping(value = "/queryMerchantPage")
    public String queryMerchant(){
        return "queryMerchant";
    }
    @RequestMapping(value = "/queryPage")
    public String query(Model model,String id,String page){
        model.addAttribute("id",id);
        model.addAttribute("page",page);
        return "Query";
    }
    @RequestMapping(value = "/queryDayPage")
    public String queryDay(Model model,String id,String mon){
        model.addAttribute("id",id);
        model.addAttribute("mon",mon);
        return "QueryDay";
    }
    @RequestMapping(value = "/queryBillPage")
    public String queryBill(Model model,String id,String mon){
        model.addAttribute("id",id);
        model.addAttribute("mon",mon);
        return "QueryBill";
    }
    @RequestMapping("/getMerchantMsg2")
    @ResponseBody
    public RestResponse getMerchantMsg(Integer page, Integer limit, HttpServletRequest request){
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        if (page==null){page=1;}
        if (limit==null){limit=10;}
        JSONObject jsonMain = new JSONObject();
        List<Merchant> merchantList = merchantService.selectAllMerchant(user.getCompanyid()+"");
        jsonMain.put("merchantList",merchantList);
        RestResponse restResponse = RestResponse.succuess();
        restResponse.setData(jsonMain);
        return restResponse;

    }

    @RequestMapping("/getSettlementById")
    @ResponseBody
    public RestResponse getSettlementById(String id, Integer page, Integer limit, String month ){
        if (page==null){page=1;}
        if (limit==null){limit=10;}
        JSONObject jsonMain = new JSONObject();
        Map<String, String> map = new HashMap<String, String>();
        if (month!=null&&!"".equals(month)) {
            String[] mons = month.split("-");
            map.put("startMonth", DateUtil.getFirstDayOfMonth(Integer.parseInt(mons[0]), Integer.parseInt(mons[1])));
            map.put("endMonth", DateUtil.getFirstDayOfMonth(Integer.parseInt(mons[0]), Integer.parseInt(mons[1])+1));
            map.put("month", month.replace("-", ""));
        }
        map.put("merchantId",id);
        List<FlowLine> flowLineList = new ArrayList<FlowLine>();
        List<FlowLine> selectList = new ArrayList<FlowLine>();
        List<Settlement> settlementList = settlementService.selectSettlementById(map);
        float rechargemoney=0;
        float settlementmoney=0;
          for (Settlement settlement:settlementList) {
                FlowLine flowLine = new FlowLine();
                flowLine.setId(settlement.getId());
                flowLine.setTime(settlement.getNowtime()+"");
                flowLine.setType(1);
                flowLine.setMoney(settlement.getCost()+"");
                settlementmoney=DateUtil.add(settlementmoney,settlement.getCost());
                flowLine.setAfter(settlement.getAftersettle()+"");
                flowLineList.add(flowLine);
            }
        List<Recharge> rechargeList = rechargeService.selectRechargeById(map);
        for (Recharge recharge: rechargeList) {
            FlowLine flowLine = new FlowLine();
            flowLine.setId(recharge.getId());
            flowLine.setTime(recharge.getRecordtime()+"");
            flowLine.setType(0);
            flowLine.setMoney(recharge.getRechargeamount()+"");
            rechargemoney=DateUtil.add(rechargemoney,recharge.getRechargeamount());
            flowLine.setAfter(recharge.getAfterrecharge()+"");
            flowLineList.add(flowLine);
        }
        Collections.sort(flowLineList, new Comparator<FlowLine>() {
            @Override
            public int compare(FlowLine o1, FlowLine o2) {
                return Integer.parseInt(o1.getTime())- Integer.parseInt(o2.getTime());
            }
        });
        int startpage = (page-1)*limit;
        int endpage =(page-1)*limit+limit>flowLineList.size()?flowLineList.size():(page-1)*limit+limit;
        for (int m=0;m<flowLineList.size();m++) {
            flowLineList.get(m).setNum(m+1);
        }
        for (int i=startpage;i<endpage;i++){
            selectList.add(flowLineList.get(i));
        }
        jsonMain.put("flowLineList",selectList);
        jsonMain.put("count",flowLineList.size());
        jsonMain.put("settlementmoney",settlementmoney);
        jsonMain.put("rechargemoney",rechargemoney);
        RestResponse restResponse = RestResponse.succuess();
        restResponse.setData(jsonMain);
        return restResponse;

    }
    @RequestMapping("/settlementBill")
    @ResponseBody
    public RestResponse settlementBill(String id, Integer page, Integer limit, String year ){
        JSONObject jsonMain = new JSONObject();
        if (year==null||"".equals(year)){
            year= DateUtil.getSysYear();
        }
        Map<String, String> map = new HashMap<String, String>();
        map.put("year", year);
        map.put("merchantId",id);
        List<Settlement> settlementList = settlementService.selectSettlementById(map);
        List<Settlement> selectDataList = new ArrayList<Settlement>();
        for (int i=1;i<13;i++){
            Settlement s = new Settlement();
            s.setMonth(Integer.parseInt(year)*100+i);
            selectDataList.add(s);
        }
        float costCount=0;
        for (Settlement settlement:settlementList) {
            for (Settlement selectdata:selectDataList) {
                if (selectdata.getMonth()==settlement.getMonth()){
                    selectdata.setEleccost(DateUtil.add(selectdata.getEleccost(),settlement.getEleccost()));
                    selectdata.setElecusage(DateUtil.add(selectdata.getElecusage(),settlement.getElecusage()));
                    selectdata.setWatercost(DateUtil.add(selectdata.getWatercost(),settlement.getWatercost()));
                    selectdata.setWaterusage(DateUtil.add(selectdata.getWaterusage(),settlement.getWaterusage()));
                    selectdata.setGascost(DateUtil.add(selectdata.getGascost(),settlement.getGascost()));
                    selectdata.setGasusage(DateUtil.add(selectdata.getGasusage(),settlement.getGasusage()));
                    selectdata.setCost(DateUtil.add(selectdata.getCost(),settlement.getCost()));
                    if (selectdata.getBeforetime()==0){
                        selectdata.setBeforetime(settlement.getBeforetime());
                    }else if(selectdata.getBeforetime()>settlement.getBeforetime()){
                        selectdata.setBeforetime(settlement.getBeforetime());
                    }
                    if (selectdata.getNowtime()==0){
                        selectdata.setNowtime(settlement.getNowtime());
                    }else if(selectdata.getNowtime()<settlement.getNowtime()){
                        selectdata.setNowtime(settlement.getNowtime());
                    }
                }
            }
            costCount=DateUtil.add(costCount,settlement.getCost());
        }
        Merchant merchant = merchantService.selectMerchantById(id);
        float balance = merchant.getBalance();
        jsonMain.put("balance",balance);
        jsonMain.put("costCount",costCount);
        jsonMain.put("settlementList",selectDataList);
        RestResponse restResponse = RestResponse.succuess();
        restResponse.setData(jsonMain);
        return restResponse;
    }

    @RequestMapping("/settlementDay")
    @ResponseBody
    public RestResponse settlementDay(String id, Integer page, Integer limit, String ym ){
        JSONObject jsonMain = new JSONObject();
        Map<String, String> map = new HashMap<String, String>();
        List<Settlement> selectList = new ArrayList<Settlement>();
        List<Settlement> selectList2 = new ArrayList<Settlement>();
        map.put("ym", ym);
        map.put("merchantId",id);
        List<Settlement> settlementList = settlementService.selectSettlementById(map);
        Map<String,Settlement> selectMap = new HashMap<String,Settlement>();
        for (Settlement settle:settlementList) {
           String time = DateUtil.stampToTime(settle.getNowtime()+"000");
           if (selectMap.get(time)!=null){
               Settlement mapSettle = selectMap.get(time);
               mapSettle.setEleccost(DateUtil.add(mapSettle.getEleccost(),settle.getEleccost()));
               mapSettle.setElecusage(DateUtil.add(mapSettle.getElecusage(),settle.getElecusage()));
               mapSettle.setWatercost(DateUtil.add(mapSettle.getWatercost(),settle.getWatercost()));
               mapSettle.setWaterusage(DateUtil.add(mapSettle.getWaterusage(),settle.getWaterusage()));
               mapSettle.setGascost(DateUtil.add(mapSettle.getGascost(),settle.getGascost()));
               mapSettle.setGasusage(DateUtil.add(mapSettle.getGasusage(),settle.getGasusage()));
               mapSettle.setCost(DateUtil.add(mapSettle.getCost(),settle.getCost()));

           }else{
               settle.setDateStr(time);
               selectMap.put(time,settle);
           }
        }
        selectMap.forEach((key, value) -> {
            selectList.add(value);
        });
        Collections.sort(selectList, new Comparator<Settlement>() {
            @Override
            public int compare(Settlement o1, Settlement o2) {
                return Integer.parseInt(o1.getDateStr().replace("-",""))- Integer.parseInt(o2.getDateStr().replace("-",""));
            }
        });
        int startpage = (page-1)*limit;
        int endpage =(page-1)*limit+limit>selectList.size()?selectList.size():(page-1)*limit+limit;
        for (int i=startpage;i<endpage;i++){
            selectList2.add(selectList.get(i));
        }
        jsonMain.put("selectList",selectList2);
        jsonMain.put("count",selectList.size());
        RestResponse restResponse = RestResponse.succuess();
        restResponse.setData(jsonMain);
        return restResponse;
    }

    @RequestMapping("/getquerybill")
    @ResponseBody
    public RestResponse getquerybill(String id, String month ){
        JSONObject jsonMain = new JSONObject();
        Map<String, String> map = new HashMap<String, String>();
        List<SingleSettlement> selectList = new ArrayList<SingleSettlement>();
        List<SingleSettlement> selectList2 = new ArrayList<SingleSettlement>();
        Map<String,SingleSettlement> selectMap = new HashMap<String,SingleSettlement>();
        map.put("merchantId",id);
        map.put("ym", month);
        String year =month.substring(0,4);
        String startMonth =month.substring(4,month.length());
        map.put("startMonth", DateUtil.getFirstDayOfMonth(Integer.parseInt(year), Integer.parseInt(startMonth)));
        map.put("endMonth", DateUtil.getFirstDayOfMonth(Integer.parseInt(year), Integer.parseInt(startMonth)+1));
        List<Settlement> settlementList = settlementService.selectSettlementById(map);
        float balance=0;
        if (settlementList!=null&&settlementList.size()>0) {
            balance=settlementList.get(0).getAftersettle();
        }
        List<SingleSettlement> SingleSettlementList = settlementService.selectSingleSettle(map);
        for (SingleSettlement singleSettlement:SingleSettlementList){
            if (selectMap.get(singleSettlement.getCode())!=null){
                SingleSettlement settlement = selectMap.get(singleSettlement.getCode());
                settlement.setCost(DateUtil.add(settlement.getCost(),singleSettlement.getCost()));
                settlement.setPowerusage(DateUtil.add(settlement.getPowerusage(),singleSettlement.getPowerusage()));
                if (singleSettlement.getTime()<settlement.getTime()){
                    settlement.setBeforereading(singleSettlement.getBeforereading());
                }else{
                    settlement.setNowreading(singleSettlement.getNowreading());
                }
            }else{
                selectMap.put(singleSettlement.getCode(),singleSettlement);
            }
        }
        selectMap.forEach((key, value) -> {
            selectList.add(value);
        });
        jsonMain.put("selectList",selectList);
        jsonMain.put("balance",balance);
        RestResponse restResponse = RestResponse.succuess();
        restResponse.setData(jsonMain);
        return restResponse;
    }
    @RequestMapping("/getReceiptMsg")
    @ResponseBody
    public RestResponse getReceiptMsg(Integer id, Integer type, HttpServletRequest request){
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        JSONObject jsonMain = new JSONObject();
        if (type == 1){
        Settlement settlement = settlementService.selectBySettlementId(id);
        Merchant merchant = merchantService.selectMerchantById(settlement.getMerchantid()+"");
        settlement.setCompanyName(merchantService.selectCompanyName(Integer.parseInt(user.getCompanyid()+"")));
        settlement.setMerchantname(merchant.getName());
        settlement.setPhone(merchant.getPhone());
            jsonMain.put("settlement",settlement);
        }else if (type == 0){
          Recharge recharge =rechargeService.selectByRechargeId(id);
            Merchant merchant = merchantService.selectMerchantById(recharge.getMerchantid()+"");
            recharge.setCompanyName(merchantService.selectCompanyName(Integer.parseInt(user.getCompanyid()+"")));
            recharge.setPhone(merchant.getPhone());
            jsonMain.put("recharge",recharge);

        }
        RestResponse restResponse = RestResponse.succuess();
        restResponse.setData(jsonMain);
        return restResponse;
    }
}
